/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
limitations under the License.*/

package zuo.biao.library.ui;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.ability.OnClickListener;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.app.Context;
import ohos.data.resultset.ResultSet;
import ohos.utils.net.Uri;
import zuo.biao.library.ResourceTable;
import zuo.biao.library.base.BaseAbility;
import zuo.biao.library.base.BaseApplication;
import zuo.biao.library.util.CommonUtil;
import zuo.biao.library.util.DataKeeper;

import java.io.File;
import java.io.IOException;

/**通用选择单张照片Activity,已自带选择弹窗
 * @author Lemon
 * <br> toActivity或startActivityForResult (SelectPictureActivity.createIntent(...), requestCode);
 * <br> 然后在onActivityResult方法内
 * <br> data.getStringExtra(SelectPictureActivity.RESULT_PICTURE_PATH); 可得到图片存储路径
 */
public class SelectPictureActivity extends BaseAbility implements Component.ClickedListener {

    //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * @param context 上下文
     * @return Intent
     */
    public static Intent createIntent(Context context) {
        String bundleName = context.getBundleName();
        Intent intent = new Intent();
        Operation operationBuilder =
                new Intent.OperationBuilder()
                        .withAbilityName("zuo.biao.library.ui.SelectPictureActivity" )
                        .withDeviceId("")
                        .withFlags(Intent.FLAG_ABILITY_NEW_MISSION)
                        .withBundleName(bundleName)
                        .build();

        intent.setOperation(operationBuilder);
        return intent;
    }

    //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setContentView(ResourceTable.Layout_select_picture_activity);
        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>
    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void initView() {//必须调用

    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>










    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    private String picturePath = "";
    @Override
    public void initData() {//必须调用

    }

    private File cameraFile;
    /**
     * 照相获取图片
     */
    @Deprecated
    public void selectPicFromCamera() {

//todo 目前没有隐式拍照获取相片的方式
//        if (!CommonUtil.isExitsSdcard()) {
//            showShortToast("SD卡不存在，不能拍照");
//            return;
//        }
//        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        // 指定调用相机拍照后照片的储存路径
//        cameraFile = new File(DataKeeper.imagePath, "photo" + System.currentTimeMillis() + ".jpg");
//        cameraFile.getParentFile().mkdirs();
//        Uri uri;
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            uri = FileProvider.getUriForFile(context, BaseApplication.getInstance().getApplicationInfo().packageName + ".fileProvider", cameraFile);
//        } else {
//            uri = Uri.fromFile(cameraFile);
//        }
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//        toActivity(intent, REQUEST_CODE_CAMERA);
    }


    /**
     * 从图库获取图片
     */
    @Deprecated
    public void selectPicFromLocal() {
//todo 目前SDK不支持，api还没有对外开放
//        Intent intent = new Intent(Intent.ACTION_PICK,
//        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        toActivity(intent, REQUEST_CODE_LOCAL);
    }

    public static final String RESULT_PICTURE_PATH = "RESULT_PICTURE_PATH";


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>








    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    private int selectRId = -1;
    @Override
    public void initEvent() {//必须调用

       DirectionalLayout directionalLayout = this.findView(ResourceTable.Id_llSelectPictureBg);
       directionalLayout.setClickedListener(this);
        new BottomMenuWindow(this)
                .setTitle("选择图片")
                .setClickListener(
                        new BottomMenuWindow.ItemClickListener() {
                            @Override
                            public void click(int position) {
                                selectRId = position;
                                switch (position) {
                                    case 0:
                                        selectPicFromCamera();
                                        break;
                                    case 1:
                                        selectPicFromLocal();
                                        break;
                                }
                            }
                        })
                .show();
    }

    //系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void onClick(Component component) {
        if (component.getId() == ResourceTable.Id_llSelectPictureBg) {
            finish();
        }
    }


    //类相关监听<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    public static final int REQUEST_TO_BOTTOM_MENU = 10;
    public static final int REQUEST_CODE_CAMERA = 18;
    public static final int REQUEST_CODE_LOCAL = 19;

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        switch (requestCode) {
            case REQUEST_CODE_CAMERA: //发送照片
                if (cameraFile != null && cameraFile.exists()) {
                    try {
                        picturePath = cameraFile.getCanonicalPath();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    setResult(-1, new Intent().setParam(RESULT_PICTURE_PATH, picturePath));
                }
            case REQUEST_CODE_LOCAL: //发送本地图片
                if (resultData != null) {
                    Uri selectedImage = resultData.getUri();
                    if (selectedImage != null) {
                        sendPicByUri(selectedImage);
                    }
                }
                break;
            default:
                break;
        }
        finish();
    }

    /**
     * 根据图库图片uri发送图片
     *
     * @param selectedImage
     */
    ResultSet resultSet;
    private void sendPicByUri(Uri selectedImage) {
        DataAbilityHelper helper = DataAbilityHelper.creator(context);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    resultSet = helper.query(selectedImage, null, null);
                } catch (DataAbilityRemoteException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        String[] allImagePath = resultSet.getAllColumnNames();
        //todo 这里需要处理一下数据allImagePath不是图片路径，需要遍历resultSet，拿到相关信息获取图片库信息

        setResult(-1, new Intent().setParam(RESULT_PICTURE_PATH, allImagePath));
    }

    /**
     * 关闭
     */
    public void finish() {
        super.onStop();
    }




    //类相关监听>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>







}
